﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GameCode.Models.PhoneApp;
using System.Net;
using System.IO;
using System.Text;
using Newtonsoft.Json;

namespace GameCode.Controllers
{
    public class PhoneAppController : Controller
    {
        //
        // GET: /PhoneApp/

        public ActionResult GetSearchValue(string callback)
        {
            GameCodeEntities entities = new GameCodeEntities();
            var systemData = (from s in entities.SystemData
                              where s.Name.Trim() == "SearchDefault"
                              select s.Value).SingleOrDefault();

            if (systemData == null)
                systemData = "";
            

            if (callback != null)
                return JavaScript(string.Format("{0}({1})", callback, JsonConvert.SerializeObject(new { search = systemData })));
            else
                return Json(new { search = systemData }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetNews(string callback)
        {
            GameCodeEntities entities = new GameCodeEntities();
            var list = (from s in entities.PageElement
                        where s.Type == "News"
                        orderby s.Seq
                        select s).ToList();

            StringBuilder sb = new StringBuilder();

            foreach (var item in list)
                sb.Append(string.Format("{0}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", item.Content.Trim()));


            if (callback != null)
                return JavaScript(string.Format("{0}({1})", callback, JsonConvert.SerializeObject(sb.ToString())));
            else
                return Json(sb.ToString(), JsonRequestBehavior.AllowGet);
        }

        public ActionResult Index(string uuid, string dtype)
        {
            IndexModel model = new IndexModel();
            if (uuid == null)
            {
                uuid = "0000000000000000-000000000000000";
                dtype = "测试";
            }

            lock (SyncObject.SyncObj)
            {

                DateTime dateTime = DateTime.Now;
                GameCodeEntities entities = new GameCodeEntities();
                var device = (from d in entities.Device
                              where d.UUID.Trim() == uuid
                              select d).SingleOrDefault();
                if (device == null)
                {
                    device = new Device();
                    device.ID = Guid.NewGuid();
                    device.InstallDate = dateTime;
                    device.UUID = uuid;
                    device.Type = dtype;
                    device.Phone = string.Empty;

                    entities.Device.AddObject(device);
                }

                device.LastAccessDate = dateTime;
                AccessLog log = new AccessLog();
                log.ID = Guid.NewGuid();
                log.DeviceID = device.ID;
                log.DateTime = dateTime;
                entities.AccessLog.AddObject(log);

                entities.SaveChanges();


                model.UUID = uuid; model.DType = dtype;
                model.CurrentMenu = "游戏推荐";
                model.AdvertiseList = (from a in entities.Advertise
                                       where a.Effective
                                       orderby a.Seq, a.Name
                                       select a).ToList();
                model.GameProjectList = (from r in entities.GameRecommend
                                         orderby r.Seq
                                         select r.GameProject).ToList();

                foreach (var project in model.GameProjectList)
                {
                    var code = (from c in entities.Code
                                where c.DeviceID == device.ID &&
                                      c.ProjectID == project.ID
                                select c).SingleOrDefault();
                    if (code == null)
                        project.State = "未领取";
                    else
                        project.State = "已领取";
                }

                return View(model);
            }
        }

        public ActionResult NewArea(string uuid, string dtype)
        {
            NewAreaModel model = new NewAreaModel();
            GameCodeEntities entities = new GameCodeEntities();
            model.UUID = uuid; model.DType = dtype;
            model.CurrentMenu = "新区资讯";
            model.List = (from n in entities.NewArea
                          where n.Effective
                          orderby n.Seq, n.GameProject.GameName
                          select n).ToList();
            return View(model);
        }

        public ActionResult MyCode(string uuid, string dtype)
        {
            MyCodeModel model = new MyCodeModel();
            GameCodeEntities entities = new GameCodeEntities();
            model.UUID = uuid; model.DType = dtype;
            model.CurrentMenu = "我的特权";
            model.GameProjectList = (from c in entities.Code
                                     where c.DeviceID != null &&
                                           c.Device.UUID == uuid
                                     orderby c.FetchDate descending
                                     select c.GameProject).ToList();

            foreach (var game in model.GameProjectList)
            {
                game.领取时间 = (from c in entities.Code
                             where c.DeviceID != null &&
                                   c.ProjectID == game.ID &&
                                   c.Device.UUID == uuid
                             orderby c.FetchDate descending
                             select c.FetchDate).SingleOrDefault().Value;
            }

            return View(model);
        }

        public ActionResult GameClassify(string uuid, string dtype)
        {
            GameClassifyModel model = new GameClassifyModel();
            GameCodeEntities entities = new GameCodeEntities();
            model.UUID = uuid; model.DType = dtype;
            model.CurrentMenu = "游戏分类";
            model.GameTypeList = (from g in entities.GameType
                                  orderby g.Seq, g.Name
                                  select g).ToList();
            return View(model);
        }

        public ActionResult GameType(string uuid, string dtype, Guid id)
        {
            GameTypeModel model = new GameTypeModel();


            DateTime dateTime = DateTime.Now;
            GameCodeEntities entities = new GameCodeEntities();

            var device = (from d in entities.Device
                          where d.UUID == uuid
                          select d).SingleOrDefault();
            model.UUID = uuid;
            model.DType = dtype;
            model.CurrentMenu = "游戏分类";
            var idList = (from r in entities.GameRefGameType
                          where r.GameTypeID == id
                          select r.GameProjectID).ToList();
            model.GameProjectList = (from r in entities.GameProject
                                     where idList.Contains(r.ID)
                                     orderby r.Seq
                                     select r).ToList();

            foreach (var project in model.GameProjectList)
            {
                var code = (from c in entities.Code
                            where c.DeviceID == device.ID &&
                                  c.ProjectID == project.ID
                            select c).SingleOrDefault();
                if (code == null)
                    project.State = "未领取";
                else
                    project.State = "已领取";
            }

            return View(model);
        }

        public ActionResult Advertise(string uuid, string dtype, Guid id)
        {
            GameCodeEntities entities = new GameCodeEntities();
            var advertise = (from p in entities.Advertise
                             where p.ID == id
                             select p).SingleOrDefault();
            if (advertise == null)
                return RedirectToAction("Error", new { uuid = uuid, dtype = dtype, message = "没有这个游戏" });

            var device = (from d in entities.Device
                          where d.UUID == uuid
                          select d).SingleOrDefault();

            HitLog log = new HitLog();
            log.ID = Guid.NewGuid();
            log.SourceType = "Advertise";
            log.SourceID = id;
            log.DateTime = DateTime.Now;
            log.DeviceID = device.ID;

            entities.HitLog.AddObject(log);
            entities.SaveChanges();

            return RedirectToAction("Game", new { uuid = uuid, id = advertise.ProjectID, islog = false });
        }

        public ActionResult Game(string uuid, string dtype, Guid id, bool islog = true)
        {
            GameModel model = new GameModel();
            model.UUID = uuid; model.DType = dtype;
            model.ID = id;
            GameCodeEntities entities = new GameCodeEntities();
            var project = (from p in entities.GameProject
                           where p.ID == id
                           select p).SingleOrDefault();
            if (project == null)
                return RedirectToAction("Error", new { uuid = uuid, dtype = dtype, message = "没有这个游戏" });

            var device = (from d in entities.Device
                          where d.UUID == uuid
                          select d).SingleOrDefault();

            if (islog)
            {
                HitLog log = new HitLog();
                log.ID = Guid.NewGuid();
                log.SourceType = "Project";
                log.SourceID = project.ID;
                log.DateTime = DateTime.Now;
                log.DeviceID = device.ID;

                entities.HitLog.AddObject(log);
                entities.SaveChanges();
            }

            model.GameName = project.GameName;
            model.RightName = project.RightName;
            model.OpenDate = project.OpenDate;
            model.GameDescription = project.GameDescription;
            model.LogoLink = project.LogoLink;
            model.WebSite = project.WebSite;
            model.GiftContent = project.GiftContent;

            model.TotalCodes = (from c in entities.Code
                                where c.ProjectID == id
                                select c).Count();
            model.RemainCodes = (from c in entities.Code
                                 where c.ProjectID == id &&
                                       c.DeviceID == null
                                 select c).Count();


            model.Code = (from c in entities.Code
                          where c.ProjectID == id &&
                                c.DeviceID == device.ID
                          select c.Code1).SingleOrDefault();

            return View(model);
        }

        public ActionResult GameFetch(string uuid, string dtype, Guid id)
        {
            GameCodeEntities entities = new GameCodeEntities();
            var project = (from p in entities.GameProject
                           where p.ID == id
                           select p).SingleOrDefault();
            if (project == null)
                return RedirectToAction("Error", new { uuid = uuid, dtype = dtype, message = "没有这个游戏" });

            var device = (from d in entities.Device
                          where d.UUID == uuid
                          select d).SingleOrDefault();

            var code = (from c in entities.Code
                        where c.ProjectID == id &&
                              c.DeviceID == device.ID
                        select c).SingleOrDefault();
            if (code == null)
            {
                lock (SyncObject.SyncCodeObject)
                {
                    code = (from c in entities.Code
                            where c.ProjectID == id &&
                                  c.DeviceID == null
                            orderby c.Seq
                            select c).FirstOrDefault();

                    if(code == null)
                        return RedirectToAction("Error", new { uuid = uuid, dtype = dtype, message = "已经没有授权码了." });

                    code.DeviceID = device.ID;
                    code.FetchDate = DateTime.Now;

                    entities.SaveChanges();
                }
            }

            return RedirectToAction("Game", new { uuid = uuid, dtype = dtype, id = id, islog = false });
        }

        public ActionResult Error(string uuid, string dtype, string message)
        {
            ErrorModel model = new ErrorModel();
            model.UUID = uuid; model.DType = dtype;
            model.Message = message;
            return View(model);
        }


        public ActionResult Search(string uuid, string dtype, string name)
        {
            IndexModel model = new IndexModel();


            DateTime dateTime = DateTime.Now;
            GameCodeEntities entities = new GameCodeEntities();
            var device = (from d in entities.Device
                          where d.UUID == uuid
                          select d).SingleOrDefault();

            model.UUID = uuid; model.DType = dtype;
            model.GameProjectList = (from r in entities.GameProject
                                     where r.GameName.Contains(name)
                                     orderby r.Seq
                                     select r).ToList();

            foreach (var project in model.GameProjectList)
            {
                var code = (from c in entities.Code
                            where c.DeviceID == device.ID &&
                                  c.ProjectID == project.ID
                            select c).SingleOrDefault();
                if (code == null)
                    project.State = "未领取";
                else
                    project.State = "已领取";
            }

            return View(model);

        }

        public ActionResult Jsonp(string url,string callback)
        {
            url = url.Replace('*', '&');
            string   Hexs= ""; 
            string   HH; 
            Encoding   GB=Encoding.GetEncoding("GB2312"); 
            Encoding   unicode=Encoding.Unicode; 

            for (int i = 0; i < url.Length; i++)
            {
                char c = url[i];
                if (Char.ConvertToUtf32(url, i) > 256)
                    Hexs += HttpUtility.UrlEncode(c.ToString());
                else
                    Hexs += c;       
            }


            string path = string.Format("Http://{0}/{1}", this.Request.Url.Authority, Hexs);
            WebResponse webResponse = null;
            
            WebRequest webRequest = WebRequest.Create(path);
            webRequest.Timeout = 50000;
            JsonpResult result = new JsonpResult();
            try 
            {
                webResponse = webRequest.GetResponse();
                if (webResponse != null)
                {
                    StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
                    result.Html = sr.ReadToEnd();
                    result.Success = true;
                    sr.Close();
                    webResponse.Close();

                }
                else 
                {
                    result.Message = "没有找到页面" ;
                }   
            }
            catch (WebException e)
            {
                result.Message = e.Message  ;
            }
            catch (Exception e)
            {
                result.Message = e.Message  ;
            }

            if (callback != null)
                return JavaScript(string.Format("{0}({1})", callback, JsonConvert.SerializeObject(result)));
            else
                return Json(result, JsonRequestBehavior.AllowGet);
        }

        public class JsonpResult
        {
            public bool Success { get; set; }
            public string Message { get; set; }
            public string Html { get; set; }
        }
    }
}
